package com.qixin.util.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @ClassName XmlUtil
 * @Description 解析xml的工具类
 * @author liaojialin
 * @Date 2017年5月27日 下午1:57:55
 * @version 1.0.0
 */
public class  XmlUtil {

	
    /**
     * @description 将xml字符串转换成map
     * @param xml
     * @return Map
     */
    public static Map<String, String> readStringXmlOut(String xml) {
        Map<String, String> map = new HashMap<String, String>();
        Document doc = null;
        try {
            // 将字符串转为XML
            doc = DocumentHelper.parseText(xml); 
            // 获取根节点 response
            Element rootElt = doc.getRootElement(); 
            // 拿到根节点的名称
            System.out.println("根节点：" + rootElt.getName()); 

            // 获取根节点下的子节点code
            Element code = rootElt.element("code");
            map.put("code", code.getText());
            // 获取根节点下的子节点message
            if ("03".equals(code.getText())){
            Iterator iter = rootElt.elementIterator("message");
            // 遍历message节点
            while (iter.hasNext()) {
                Element recordEle = (Element) iter.next();
                // 拿到message节点下的子节点desmobile值
                String desmobile = recordEle.elementTextTrim("desmobile"); 
                String msgid = recordEle.elementTextTrim("msgid"); 
                System.out.println("desmobile:" + desmobile);
                System.out.println("msgid:" + msgid);
                map.put("desmobile", desmobile);
                map.put("msgid", msgid);
            }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}
